import React, { useEffect , useState ,useRef} from 'react'
import CanvasDraw  from 'react-canvas-draw';
import { Divider , Form ,Input ,Button ,DatePicker , Upload , message} from 'antd';
import moment from 'moment';
import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';
import _ from 'lodash'
import request from '@/utils/request';
import { ConsoleSqlOutlined, DeleteOutlined } from '@ant-design/icons'
import styles from './style.less';
const qrForm = (props) => {
    const [reciptImg, setReciptImg] = useState() //签收单图片
    const [signature,setSignature] = useState()  //签名图片
    const [isSubmit ,setIsSubmit] = useState(false)
    const [form] = Form.useForm(); // 利用Form引入也可
    const signCanvas= useRef();
    useEffect(() => {
        document.title = '发票回执'
        
    }, [])
    //base64转二进制
    const dataURLtoFile = (dataurl, filename)=> { 
	    var arr = dataurl.split(','),
	        mime = arr[0].match(/:(.*?);/)[1],
	        bstr = atob(arr[1]),
	        n = bstr.length,
	        u8arr = new Uint8Array(n);
	    while (n--) {
	        u8arr[n] = bstr.charCodeAt(n);
	    }
	    return new File([u8arr], filename, { type: mime });
    }
    const onFinish = async(values) => {
        if(isSubmit){
            return
        }
        if(!signature){
            message.warn('请收件人签名',2)
            setIsSubmit(false)
            return
        }
        setIsSubmit(true)
        const hide = message.loading('正在提交，请耐心等待', 0);
        const { invoiceNum , invoiceCom  } = values
        const endDate = moment(values.endDate).format('YYYY-MM-DD')
        const param = {
            invoiceNum,
            invoiceCom,
            endDate,
            reciptImg,
            signatureImg:dataURLtoFile(signature,'签名.jpg')
        }
        const forms = new FormData();
        for (let key in param) {
            forms.append([key], param[key])
        }
        
        const res = await request('/invoice/receipt/',{
            method:'POST',
            data: forms
            
        })
        hide()
        if(res?.status == '200'){
            message.success('提交成功')
            form.resetFields()
            handleClear()
        }else{
            message.warn('提交失败，请联系管理员')
        }
        setIsSubmit(false)

      };
    
    const handleChange = () =>{
        // console.log(signCanvas)
        const pic = signCanvas.current.canvas.drawing.toDataURL("image/png")
        setSignature(pic)
    }
    const handleClear = () =>{
        setSignature(undefined)
    }  
    /**
     * 发票号码输入框内容改变
     */
    const handleNumInputChange = _.debounce(async function(e) {
        const res = await request('/invoice/getproperty/',{
            method:'POST',
            data:{
                invoice:e.target.value
            }
        })
        if(res.invoicePrice != ''){
            const { invoicePrice , startDate , invoiceCom} = res
            form.setFieldsValue({
                invoicePrice,
                startDate,
                invoiceCom
            })
        }else{
            form.setFieldsValue({
                invoicePrice:undefined,
                startDate:undefined,
                invoiceCom:undefined
            })
        }
      }, 1000, {
        leading: false,
        trailing: true
      })
    return (
        <div>
            <div style={{minHeight:'30px',backgroundColor:'black'}}>

            </div>
            <h1 style={{paddingLeft:'15px'}}>发票回执</h1>
            <Divider orientation="right">昆明喜田科技有限公司</Divider>
            <Form
                name="basic"
                form={form}
                labelCol={{ span: 24 }}
                wrapperCol={{ span: 24 }}
                onFinish={onFinish}
                initialValues={{
                    endDate:moment(new Date(),'YYYY/MM/DD')
                }}
                autoComplete="off"
                style={{padding:'22px'}}
            >
                <Form.Item
                    label="发票号码"
                    name="invoiceNum"
                    rules={[{ required: true, message: '请输入正确发票号码' }]}
                >
                    <Input placeholder='输入八位数发票号码' onChange={handleNumInputChange}/>
                </Form.Item>

                <Form.Item
                    label="受票单位"
                    name="invoiceCom"
                    rules={[{ required: true, message: '请输入正确发票号码' }]}
                >
                    <Input disabled={true} placeholder='填写发票号码正确，公司名自动生成，不需填写'/>
                </Form.Item>
                <Form.Item
                    label="发票金额"
                    name="invoicePrice"
                    rules={[{ required: true, message: '请输入正确发票号码' }]}
                >
                    <Input disabled={true} placeholder='填写发票号码正确，余额自动生成，不需填写'/>
                </Form.Item>
                <Form.Item
                    label="开票日期"
                    name="startDate"
                    rules={[{ required: true, message: '请输入正确发票号码' }]}
                >
                    <Input disabled={true} placeholder='自动生成，不需填写'/>
                </Form.Item>
                <div   
                >
                    <div><span style={{color:'red'}}>*</span>&nbsp;收件人签名</div>
                    <div style={{border:'1px solid black'}}>
                        <CanvasDraw
                            ref={signCanvas}
                            brushColor="#000"
                            brushRadius={3}
                            lazyRadius={0}
                            canvasWidth={"100%"}
                            canvasHeight={300}
                            onChange={handleChange}
                            hideGrid={true}
                        />
                        <div style={{textAlign:'right'}}> 
                            <DeleteOutlined style={{fontSize:'24px',padding:'5px'}} onClick={()=>{
                                signCanvas.current.clear()
                                handleClear()
                                }}/>
                        </div>
                    </div>
                </div>
                <Form.Item
                    label="收件日期"
                    name="endDate"
                    rules={[{ required: true, message: '请选择收件日期' }]}
                >
                        <DatePicker locale={locale} style={{width:'100%'}} />
                </Form.Item>
                <Form.Item
                    label="发票签收回执单拍照上传"
                    name="receiptPic"
                    valuePropName="file"
                    rules={[{ required: true, message: '请上传签收回执单'}]}
                >
                    <Upload accept="image/*" capture="camera" maxCount={1} listType='picture-card' beforeUpload={file => setReciptImg(file)}>
                            点击进行上传
                    </Upload>
                </Form.Item>

                <Form.Item wrapperCol={{  span: 24 }}>
                    <Button type="primary" htmlType="submit" style={{width:'100%'}}>
                        提交
                    </Button>
                </Form.Item>
            </Form>
        </div>
    )
}
export default qrForm